package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.dto.ApiResponse;
import com.it.schoolhomeos.dto.LoginRequest;
import com.it.schoolhomeos.dto.UserDTO;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * 处理用户登录、注销等认证相关请求
 * 提供用户身份验证和会话管理功能
 */
@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证管理", description = "用户登录、注销等认证相关接口")
@RequiredArgsConstructor
public class AuthController {

    private final AuthenticationManager authenticationManager;
    private final UserService userService;

    /**
     * 用户登录接口
     * 
     * @param loginRequest 包含用户名和密码的登录请求对象
     * @return 登录成功后返回用户信息
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口，返回用户信息")
    public ApiResponse<UserDTO> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 进行身份认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );
            
            // 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取用户信息
            UserDTO userDTO = userService.getCurrentUser();
            
            return ApiResponse.success("登录成功", userDTO);
        } catch (BadCredentialsException e) {
            return ApiResponse.error(400, "用户名或密码错误");
        } catch (Exception e) {
            return ApiResponse.error(500, "登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户注销接口
     * 
     * @return 注销结果
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销", description = "用户注销接口")
    public ApiResponse<Void> logout() {
        SecurityContextHolder.clearContext();
        return ApiResponse.<Void>success("注销成功", null);
    }

    /**
     * 获取当前登录用户信息接口
     * 
     * @return 当前登录用户的信息
     */
    @GetMapping("/current-user")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息")
    public ApiResponse<UserDTO> getCurrentUser() {
        UserDTO userDTO = userService.getCurrentUser();
        return ApiResponse.success(userDTO);
    }
} 